<template>
	<view class="charge">
		<!-- #ifdef MP-WEIXIN -->
		<view class="head" :style="{height: pHeight + tHeight + 'px'}">
			<view class="xztitle" :style="[{height: pHeight + 'px', top: tHeight + 'px',lineHeight: pHeight + 'px'}]">
				手机充电
				<view class="iconfont icon-dayuhao1" @click="fanhui"></view>
			</view>
		</view>
		<view class="headtop" :style="{marginTop: pHeight + tHeight + 'px'}">
			<image :src="baseUrl + '/wximage/img/xian_chongdianbj.png'"></image>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<view class="headtop">
			<image :src="baseUrl + '/wximage/img/xian_chongdianbj.png'"></image>
		</view>
		<!-- #endif -->
		<view class="jiaocheng">
			<image :src="baseUrl + '/wximage/img/xian_chongdiansp.png'" class="bj"></image>
			<view class="wenzi">
				使用视频教程
			</view>
			<view class="guankan" @click="topage('/pagesA/home/second/video')">立即观看</view>
		</view>
		<view class="chargelist">
			<view class="list" v-for="(item,index) in combo" :key="index">
				<view class="top clearfix">
					<image :src="baseUrl + '/wximage/img/xian_chongdian1.png'" class="fl"></image>
					<view class="name fl">充电套餐</view>
				</view>
				<view class="center clearfix">
					<view class="desc fl">{{item.money}}元{{item.time}}小时</view>
					<view class="price fr">¥{{item.money}}</view>
				</view>
				<view class="bottom" @click="orderPrice(item)">充电支付（ <text v-if="svip==1">0</text> <text
						v-else>{{item.money}}</text> 元）</view>
			</view>
		</view>
		<view class="kefu" @click="call">
			<image :src="baseUrl + '/wximage/img/xian_kefu.png'"></image>
			<view class="desc">客服</view>
		</view>
		<view class="beijing" v-if="hidden == true"></view>
		<view class="tankuang" v-if="hidden == true">
			<image :src="baseUrl + '/wximage/img/xian_weitu.png'" class="tankuangbj"></image>
			<view class="con">
				<view class="title">蓝牙连接失败</view>
				<view class="detail">
					<view class="desc">1.请确认充电器插上电源并且指示灯亮起</view>
					<view class="desc">2.请确认已经打开<text>【蓝牙】</text>和<text>【定位】</text></view>
					<view class="yuxun" @click="dakai">点击打开 ->【微信蓝牙设置】</view>
					<view class="yuxun" @click="yunxu">点击允许 ->【小程序使用蓝牙】</view>
				</view>
				<image :src="baseUrl + '/wximage/img/xian_daotu.png'" class="zhishi"></image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseUrl: getApp().globalData.baseUrl,
				headerTop: 0,
				pHeight: 0,
				tHeight: 0,
				phone: '',
				hidden: false,
				qrcode: '',
				danhao: '',
				orderInterval: null,
				charger_number: '',
				combo: [],
				deviceInfo: {},
				getBlueIntervalNum: 1,
				getBluetoothIntval: null,
				deviceId: '',
				connectedDeviceId: '', //链接的id
				services: '',
				notifyCharacteristicsId: '',
				writeCharacteristicsId: '',
				characteristics: '',
				notifyServicweId: '',
				writeServicweId: '',
				sendNum: 0,
				type: 1,
				sendProgress_status: false,
				deviceReset: 0,
				orderOk: 0,
				svip: 0
			}
		},
		beforeDestroy() {
			if (this.getBluetoothIntval) {
				clearInterval(this.getBluetoothIntval);
				this.getBluetoothIntval = null;
			}
			if (this.orderInterval) {
				clearInterval(this.orderInterval);
				this.orderInterval = null;
			}
		},
		onLoad(options) {
			this.qrcode = options.qrcode;
			// 头部距离
			let res = uni.getSystemInfoSync() ///微信api方法
			let titleH;
			if (res && res['system']) {
				// 判断是否是安卓操作系统 （标题栏苹果为44px,安卓为48px）
				if (res['system'].indexOf('Android') > 0) {
					titleH = 48
				} else {
					titleH = 46
				}
				this.headerTop = titleH + res['statusBarHeight']
				this.pHeight = titleH
				this.tHeight = res['statusBarHeight']
			}

			// #ifdef MP-ALIPAY
			my.setNavigationBar({
				frontColor: '#333333',
				backgroundColor: '#cefbfd',
			})
			// 设置导航栏标题
			my.setNavigationBar({
				title: '手机充电'
			})
			// #endif
			//查询一下充电线信息和收费信息
			this.chongInfo();
			//查询一下用户信息判断是否是会员
			this.membershipcardInfo();
			this.openjianceblue();
		},
		methods: {
			
			openjianceblue() {
				console.log("检测蓝牙是否打开了呀");
				var that = this;
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						uni.showToast({
							title: '初始化成功',
							icon: 'success',
							duration: 800
						})
					},
					fail: function(res) { //如果手机上的蓝牙没有打开，可以提醒用户
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						});
						that.hidden = true;
					}
				})
			},
			
			//查询用户信息
			membershipcardInfo() {
				var that = this;
				let formData = {
					qrcode: that.qrcode,
					userid: uni.getStorageSync('user_id'),
				};
				that.request({
					url: '/orderx/membershipcardinfo',
					data: formData, //充电线
					method: "POST"
				}).then(res => {
					console.log(res);
					that.svip = res.data.data.svip;
					// console.log("打印一下是否是svip");
					// console.log(that.svip);
				})
			},
			//查询订单是否支付
			orderInfo(danhao) {
				var that = this;
				that.orderInterval = setInterval(() => {
					that.request({
						url: '/orderx/orderinfo1',
						data: {
							'danhao': danhao
						}, //充电线
						method: "POST"
					}).then(res => {
						if (res.data.data.status == 5) {
							if (that.orderOk == 0) { //订单是否ok
								that.orderOk = 1;
								that.onLocationAuth();
								clearInterval(that.orderInterval);
							}
						}
					});
				}, 300)
			},
			//支付创建订单
			orderPrice(item) {
				// console.log("会员");
				// console.log(that.svip);
				var that = this;
				let formData = {
					charger_number: that.charger_number,
					money: item.money,
					time: item.time,
					type: 3,
					userid: uni.getStorageSync('user_id'),
					qrcode: that.qrcode,
					svip: that.svip
				};
				that.request({
					url: '/orderx/lineorder',
					data: formData, //充电线
					method: "POST"
				}).then(res => {
					if (res.data.code == 200) {
						var danhao = res.data.data.orderinfo.danhao;
						that.danhao = danhao;
						//判断一下
						if (res.data.data.orderinfo.member_id == 0) {
							// #ifdef MP-WEIXIN
							uni.requestPayment({
								'timeStamp': res.data.data.payinfo.timeStamp,
								'nonceStr': res.data.data.payinfo.nonceStr,
								'package': res.data.data.payinfo.package,
								'signType': 'MD5',
								'paySign': res.data.data.payinfo.paySign,
								'success': function(res) {
									uni.showLoading({
										title: '正在查询',
									})

									that.orderInfo(danhao);
								},
								'fail': function(res) {
									uni.showToast({
										title: '支付失败',
										icon: 'none'
									})
								}
							});
							// #endif

							// #ifdef MP-ALIPAY
							my.tradePay({
								tradeNO: res.data.data.payinfo.trade_no,
								success: (res1) => {
									if (res1.resultCode == 9000) {
										uni.showLoading({
											title: '正在查询',
										})

										that.orderInfo(danhao);
									} else {
										// 支付不成功，具体原因看返回，去对照文档
									}
								},
								fail: (err1) => {
									console.log(err1);
								}
							});
							// #endif
						} else {
							that.orderInfo(danhao);
						}
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
					return false;
				});
			},
			// 客服
			call() {
				let phone = this.phone;

				uni.makePhoneCall({
					phoneNumber: phone,
					success() {

					}
				})
			},
			onLocationAuth() {
				const _this = this // 下边this 为undefined

				// #ifdef MP-WEIXIN
				uni.authorize({
					scope: 'scope.userLocation', // 获取地理信息必填的参数，其它参数见文档
					success(res) {
						_this.getLocationFn()
					},
					// 授权失败
					fail(err) {
						err = err['errMsg']
						uni.showModal({
							title: '温馨提示',
							content: '为享受智能小程序，您必须授权!',
							showCancel: false,
							confirmText: '确认授权'
						}).then(res => {
							if (res[1]['confirm']) { // 点击了确认按钮时
								uni.openSetting({
									success(res) {
										if (res.authSetting == 'scope.userLocation: true') {
											_this.getLocationFn()
										}
									}
								})
							}
						})
					}
				})
				// #endif

				// #ifdef MP-ALIPAY
				_this.getLocationFn()
				// #endif
			},
			getLocationFn() {
				const _this = this

				// #ifdef MP-WEIXIN
				uni.getLocation({
					type: 'gcj02', // <map> 组件默认为国测局坐标gcj02
					altitude: true,
					success(res) {
						//初始化蓝牙
						_this.openBluetooth();
					}
				})
				// #endif

				// #ifdef MP-ALIPAY
				my.getLocation({
					type: 1, // 获取经纬度和省市区县数据
					success: (res) => {
						//初始化蓝牙
						_this.openBluetooth();
					},
					fail: (error) => {
						console.error('定位失败: ', JSON.stringify(error));
					},
					complete: () => {},
				});
				// #endif
			},
			openBluetooth() {
				var that = this;
				
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						uni.showToast({
							title: '初始化成功',
							icon: 'success',
							duration: 800
						})
						that.findBlue(); //2.0
					},
					fail: function(res) { //如果手机上的蓝牙没有打开，可以提醒用户
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						});
					}
				})
			},
			//搜索附近蓝牙设备
			findBlue() {
				var that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success: function(res) {
						uni.showLoading({
							title: '正在搜索设备',
						})
						//搜索附近蓝牙设备
						that.getBlue() //3.0
					}
				})
			},
			/**
			 * 获取搜索到的蓝牙设备列表
			 */
			getBlue() {
				let that = this
				that.getBlueIntervalNum = 1
				that.getBluetoothIntval = setInterval(() => {
					that.getBlueIntervalNum++
					uni.getBluetoothDevices({
						success: function(res) {
							let code_sn = that.charger_number
							if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) { //查询8次还没有就终止
								uni.showToast({
									title: '未查找到设备',
									type: 'error',
									icon: 'none'
								});
								return false;
							}
							
							console.log(res.devices);

							if (res.devices.length > 0) {
								if (res.devices.length) {
									for (let i = 0; i < res.devices.length; i++) {
										console.log("查看一下搜索道德蓝牙设备")
										console.log(code_sn);
										console.log(res.devices[i].localName);
										console.log(code_sn === res.devices[i].localName);
										console.log("查看一下搜索道德蓝牙设备")
										console.log(code_sn);
										console.log(res.devices[i].localName);
										console.log(code_sn === res.devices[i].localName);
										if ((code_sn === res.devices[i].localName || code_sn === res
												.devices[i].name)) {
											console.log("执行这个了嗷")
											that.deviceId = res.devices[i].deviceId
											clearInterval(that.getBluetoothIntval)
											setTimeout(() => {
												console.log("执行到这里了吗");
												that.connectTO()
											}, 100)
											break
										}

										if ((code_sn === res.devices[i].localName || code_sn === res
												.devices[i].name) && !that.deviceId) {
											that.deviceId = res.devices[i].deviceId
											clearInterval(that.getBluetoothIntval)
											setTimeout(() => {
												that.connectTO()
											}, 100)
											break
										}
									}
									console.log('333333333333333=====')
								} else if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
									clearInterval(that.getBluetoothIntval)
									uni.showToast({
										title: '未查找到设备',
										type: 'error',
										icon: 'none'
									});
									console.log('222222222222222222=====')
								}
							} else if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
								clearInterval(that.getBluetoothIntval)
								uni.showToast({
									title: '未查找到设备',
									type: 'error',
									icon: 'none'
								});
								console.log('11111111111111=====')
							}
						},
						fail: function(err) {
							that.getBlueIntervalNum++
							if (that.getBlueIntervalNum > 8 || !that.getBlueIntervalNum) {
								clearInterval(that.getBluetoothIntval)
								uni.showToast({
									title: '未查找到设备',
									type: 'error',
									icon: 'none'
								});
							}
							console.log(err, '获取蓝牙设备列表失败=====' + that.getBlueIntervalNum)
						}
					})
				}, 2000)
			},
			/**
			 * 连接蓝牙
			 */
			connectTO() {
				let that = this
				that.connect_num = that.connect_num || 1
				that.connectedDeviceId = that.deviceId
				uni.createBLEConnection({
					deviceId: that.connectedDeviceId,
					success: function(res) {
						that.getBLEDeviceServices()
						uni.stopBluetoothDevicesDiscovery({
							success: function(res) {
								console.log(res, '链接蓝牙成功，停止搜索成功')
							},
							fail: function(res) {
								console.log(res, '链接蓝牙成功，停止搜索失败')
							}
						})
					},
					fail: function(err) {
						that.postLog(2, err)
						if (err.errCode == -1 && err.errMsg.indexOf('already connect') > -1) {
							that.getBLEDeviceServices()
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log(res, '蓝牙已连接过，停止搜索成功')
								},
								fail: function(res) {
									console.log(res, '蓝牙已连接过，停止搜索失败')
								}
							})
						} else {
							that.connect_num++
							// console.log(err, '链接蓝牙失败===' + that.connect_num)
							if (that.connect_num > 3 || !that.connect_num) {
								uni.showToast({
									title: '蓝牙连接失败',
									type: 'error',
									icon: 'none'
								});
							} else {
								setTimeout(() => {
									that.connectTO()
								}, 1000)
							}
						}
					}
				})
			},

			/**
			 * 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service
			 */
			getBLEDeviceServices() {
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: that.connectedDeviceId,
						success: function(res) {
							// console.log(res, '获取蓝牙设备的service服务=========ok')
							that.services = res.services
							if (res.services.length > 0) {
								that.getBLEDeviceCharacteristics(0)
							} else {
								that.showModal('蓝牙服务获取失败', 2)
							}
						},
						fail: function(err) {
							that.showModal('蓝牙服务获取失败', 2)
							// console.log(err, '获取蓝牙设备的service服务____err')
						}
					})
				}, 100)
			},

			/**
			 * 7.获取蓝牙设备特征值
			 * 获取到的特征值有多个，最后要用的事能读，能写，能监听的那个值的uuid作为特征值id，
			 */
			getBLEDeviceCharacteristics(services_num) {
				let that = this
				that.notifyCharacteristicsId = ''
				that.writeCharacteristicsId = ''
				uni.getBLEDeviceCharacteristics({
					deviceId: that.connectedDeviceId,
					serviceId: that.services[services_num].uuid,
					success: function(res) {
						console.log(res, '获取蓝牙设备特征值成功==========')
						that.characteristics = res.characteristics;
						
						// #ifdef MP-WEIXIN
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							console.log(item)
							if ((item.properties.read && item.properties.write && item.properties.notify) || (
									item.uuid.indexOf("FFF4") > -1)) {
									console.log(item.uuid.indexOf("FFF4"))	
								/* 获取支持 notify 或者 indicate 的特征值 */
								that.notifyCharacteristicsId = item.uuid
								that.notifyServicweId = that.services[services_num].uuid
							}
							if ((item.properties.write) && !that.writeCharacteristicsId) {
								that.writeCharacteristicsId = item.uuid
								that.writeServicweId = that.services[services_num].uuid
							}
							
							console.log(that.notifyCharacteristicsId + '11111' + that.writeCharacteristicsId)
							if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
								that.notifyBLECharacter()
								break
							}
						}
						if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
							services_num = services_num + 1
							if (services_num < that.services.length) {
								that.getBLEDeviceCharacteristics(services_num)
							} else {
								
								that.showModal('蓝牙特征值获取失败', 2)
							}
						}
						// #endif
						
						// #ifdef MP-ALIPAY
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							console.log(item)
							if ((item.properties.read && item.properties.write && item.properties.notify) || (
									item.characteristicId.indexOf("FFF4") > -1)) {
									console.log(item.characteristicId.indexOf("FFF4"))	
								/* 获取支持 notify 或者 indicate 的特征值 */
								that.notifyCharacteristicsId = item.characteristicId
								that.notifyServicweId = that.services[services_num].uuid
							}
							if ((item.properties.write) && !that.writeCharacteristicsId) {
								that.writeCharacteristicsId = item.characteristicId
								that.writeServicweId = that.services[services_num].uuid
							}
							
							console.log(that.notifyCharacteristicsId + '11111' + that.writeCharacteristicsId)
							if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
								that.notifyBLECharacter()
								break
							}
						}
						if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
							services_num = services_num + 1
							if (services_num < that.services.length) {
								that.getBLEDeviceCharacteristics(services_num)
							} else {
								
								that.showModal('蓝牙特征值获取失败', 2)
							}
						}
						// #endif
						// for (var i = 0; i < res.characteristics.length; i++) {
						// 	let item = res.characteristics[i]

						// 	if ((item.properties.read && item.properties.write && item.properties.notify) || (
						// 			item.uuid.indexOf("FFF4") > -1)) {
						// 		/* 获取支持 notify 或者 indicate 的特征值 */
						// 		that.notifyCharacteristicsId = item.uuid
						// 		that.notifyServicweId = that.services[services_num].uuid
						// 	}
						// 	if ((item.properties.write) && !that.writeCharacteristicsId) {
						// 		that.writeCharacteristicsId = item.uuid
						// 		that.writeServicweId = that.services[services_num].uuid
						// 	}
						// 	if (that.notifyCharacteristicsId && that.writeCharacteristicsId) {
						// 		that.notifyBLECharacter()
						// 		break
						// 	}
						// }
						// if (!that.notifyCharacteristicsId || !that.writeCharacteristicsId) {
						// 	services_num = services_num + 1
						// 	if (services_num < that.services.length) {
						// 		that.getBLEDeviceCharacteristics(services_num)
						// 	} else {
						// 		that.showModal('蓝牙特征值获取失败', 2)
						// 	}
						// }
					},
					fail: function(err) {
						that.showModal('蓝牙特征值获取失败', 2)
						console.log(err, '获取蓝牙设备特征值====err')
					}
				})
			},
			/**
			 * 启用低功耗蓝牙设备特征值变化时的 notify 功能
			 * 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据
			 */
			notifyBLECharacter() {
				console.log("开始启用充电功能了？？？");
				let that = this;
				let error = {
					10000: '未初始化蓝牙适配器',
					10001: '当前蓝牙适配器不可用',
					10002: '没有找到指定设备',
					10003: '连接失败',
					10004: '没有找到指定服务',
					10005: '没有找到指定特征值',
					10006: '当前连接已断开',
					10007: '当前特征值不支持此操作',
					10008: '其余所有系统上报的异常',
					10009: '系统版本低于4.3不支持蓝牙监听功能',
					10012: '连接超时',
					10013: '连接deviceId为空或者是格式不正确',
				};
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.connectedDeviceId,
					serviceId: that.notifyServicweId,
					characteristicId: that.notifyCharacteristicsId,
					complete(res) {
						console.log(res, '启用低功耗蓝牙设备监听=====complete')
						if (res.errCode >= 10000) {

							that.showModal(error[res.errCode] || '很抱歉，设备通讯超时', 2)
						} else {
							console.log("发送充电功能上")
							// console.log(pData);
							//判断一下设备

							console.log("发送充电功能");

							that.setSendStr()

						}
					}
				})
			},


			/**
			 * 监听手机蓝牙设备数据变化
			 */
			onBLECharacter() {
				let that = this;
				let type = that.type;
				var hexVal = '',
					endVal = ''
				uni.onBLECharacteristicValueChange((res) => {
					console.log(res, '监听手机蓝牙设备的数据变化===')
					// // if(that.bluetooth_name) {
					// //   hexVal = that.ab2hex(res.value)
					// //   endVal = hexVal.substr(4, 2)
					// // } else {
					// #ifdef MP-WEIXIN
					hexVal = '0x' + that.ab2hex(res.value)
					// #endif
					
					// #ifdef MP-ALIPAY
					hexVal = '0x' + res.value;
					// #endif
					hexVal = hexVal.toLowerCase()
					//查看一下返回的数据ok
					if (hexVal.substr(0, 4) == '0xf1') {
						endVal = hexVal.substr(6, 2)
					} else {
						//密码线是从第6位截取两位
						endVal = hexVal.substr(6, 2)
						// endVal = hexVal.substr(4, 2)
					}
					// }

					// console.log(hexVal)
					console.log(endVal)
					console.log("查看启动充电是否成功或者失败");
					if (endVal == '00' || endVal == '0000') {
						console.log('命令成功拉')

						that.sendProgress_status = true;


						//      if(that.deviceReset){
						//        app.getPage(that.onPageNum).reloadCode().then(() => {
						//          app.getPage(that.onPageNum).getSendMsg().then(msg => {
						//            that.setSendStr(msg)
						//          })
						//        })
						//      }else{
						//        // 充电成功 或 结束成功
						//          that.sendProgress_status= true;
						// //跳转页面好了
						//      }
						uni.showModal({
							title: '温馨提示',
							content: `启动充电成功`,
							showCancel: false,
							confirmText: '确定',
							success() {
								// app.goBack()
								uni.redirectTo({
									url: '/pages/order/linedetail?danhao=' + that.danhao
								})
							}
						})
					} else {
						// 充电失败 或 结束失败
						// if(type == 3){
						// app.getPage(2).postEndOrder()
						// } else if(type == 4){
						uni.showModal({
							title: '温馨提示',
							content: `启动充电失败`,
							showCancel: false,
							confirmText: '确定',
							success() {
								// app.goBack()
								uni.redirectTo({
									url: '/pages/order/linedetail?danhao=' + that.danhao
								})
							}
						})
						// } 
					}

					// console.log(that.danhao)


				})
			},


			/**
			 * 拼接发送的代码
			 * @param {*} msg 
			 */
			setSendStr(msg) {
				this.onBLECharacter();
				if (msg) {
					setTimeout(() => {
						this.sendData(msg)
					}, 50)
				} else {
					//请求一下接口向蓝牙充电发送数据
					this.request({
						url: '/wxdevice/sendyishengyuan',
						data: {
							code_sn: this.charger_number,
							danhao: this.danhao
						},
						method: "POST"
					}).then(res => {
						if (res.data.code == 200) {
							let str = res.data.data;
							setTimeout(() => {
								this.sendData(str)
							}, 50)
						} else {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						}
						return false;
					});
				}
			},

			/**
			 * 向蓝牙设备发送数据
			 */
			sendData(str) {
				let that = this
				// 每哥字节前面都要0X  或者都不要
				// var token = "01 00430 2 05a4AEAA";
				//测试  之前二合一好使的
				// var token = "010043020005C151";
				var token = str;
				//密码二合一的
				//  var token = "F1010001000A"; //1分钟的
				// var token = "F10105A0000A"; //1440分钟的
				// var token = "050505050505";//结束订单的东西
				// console.log('sendStr=========', token)

				let buffer = new ArrayBuffer(token.length / 2)
				let dataView = new DataView(buffer)
				var buf = []
				for (var i = 0; i < token.length; i = i + 2) {
					buf.push(token.substr(i, 2))
				}

				for (var i = 0; i < buf.length; i++) {
					dataView.setUint8(i, "0x" + buf[i].toLowerCase());
				}


				// var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
				//   console.log("打印一下子");
				//   console.log(parseInt(h, 16));
				//   return parseInt(h, 16)
				// }))


				this.request({
					url: '/wxdevice/lineinfo',
					data: {
						qrcode: this.qrcode
					},
					method: "POST"
				}).then(res => {
					if (res.data.code == 200) {
						console.log(res.data.data)
						// this.arrpop = {};
						this.combo = res.data.data.combo;
						this.deviceInfo = res.data.data.device;
						this.charger_number = this.deviceInfo.charger_number;
						console.log(this.charger_number);
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
				});

				that.sendNum = that.sendNum || 1
				console.log('发送message======' + that.sendNum)
				// console.log(typedArray.buffer)
				that.BLEValue = ''
				wx.writeBLECharacteristicValue({
					deviceId: that.connectedDeviceId,
					serviceId: that.writeServicweId,
					characteristicId: that.writeCharacteristicsId,
					value: buffer,
					success(res) {
						console.log("发送成功啦啦啦")
						console.log(res);
						console.log(res, 'message发送成功')
					},
					fail(res) {
						console.log('发送失败');
						console.log(res);
						if (that.sendNum > 3 || !that.sendNum) {
							that.showModal('非常抱歉，发送信息失败', 2)
						} else {
							that.sendNum++
							that.sendData(str)
						}
						console.log(res, 'message发送失败')
					},
					complete(e) {
						that.onBLEFail = false
						console.log(e, 'message发送complete')
					}
				})
			},

			/**
			 * ArrayBuffer转16进制字符串示例
			 * @param {*} buffer 
			 */
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},

			chongInfo() {
				this.request({
					url: '/wxdevice/lineinfo',
					data: {
						qrcode: this.qrcode
					},
					method: "POST"
				}).then(res => {
					if (res.data.code == 200) {
						this.combo = res.data.data.combo;
						this.deviceInfo = res.data.data.device;
						this.charger_number = this.deviceInfo.charger_number;
						this.phone = res.data.data.station.phone;
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
				});
			},
			//打开蓝牙设备
			dakai() {
				uni.openSystemBluetoothSetting()
			},
			// 允许授权
			yunxu() {
				uni.openSetting()
			},
			fanhui() {
				uni.navigateBack()
			},
			topage(url) {
				uni.navigateTo({
					url
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.charge {
		width: 100%;
		margin: 0 auto;

		.head {
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 99;
			background: linear-gradient(90deg, #c5f9ff, #ddfcf8);

			.xztitle {
				position: fixed;
				left: 0%;
				top: 0;
				width: 100%;
				text-align: center;
				color: #333333;
				font-size: 32rpx;
			}

			.iconfont {
				position: absolute;
				top: 0;
				left: 14rpx;
				font-size: 44rpx;
			}
		}

		.headtop {
			width: 100%;

			image {
				width: 100%;
				height: 230rpx;
				display: flex;
			}
		}

		.jiaocheng {
			width: 94.7%;
			margin: 0 auto;
			margin-top: 20rpx;
			margin-bottom: 20rpx;
			position: relative;

			.bj {
				width: 100%;
				height: 160rpx;
				display: flex;
			}

			.wenzi {
				position: absolute;
				top: 60rpx;
				left: 190rpx;
				font-size: 36rpx;
				font-weight: 700;
				color: #333333;
			}

			.guankan {
				position: absolute;
				top: 54rpx;
				right: 40rpx;
				width: 180rpx;
				text-align: center;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 16rpx;
				font-size: 28rpx;
				background: #46C7E2;
				color: #FFFFFF;
			}
		}

		.chargelist {
			width: 94.7%;
			margin: 0 auto;
			margin-bottom: 40rpx;

			.list {
				width: 100%;
				margin: 0 auto;
				background: #F2FFFE;
				border-radius: 20rpx;
				padding: 30rpx 30rpx 20rpx 30rpx;
				box-sizing: border-box;
				margin-bottom: 20rpx;

				.top {
					height: 52rpx;
					line-height: 52rpx;
					margin-bottom: 20rpx;

					image {
						width: 52rpx;
						height: 52rpx;
						margin-right: 12rpx;
					}

					.name {
						font-size: 32rpx;
						font-weight: 700;
						color: #333333;
					}
				}

				.center {
					width: 100%;
					padding: 0 20rpx 20rpx 20rpx;
					box-sizing: border-box;
					border-bottom: 1rpx solid #D8D8D8;

					.desc {
						font-size: 24rpx;
						color: #666666;
						margin-top: 2rpx;
					}

					.price {
						font-size: 28rpx;
						color: #333333;
						font-weight: 700;
					}
				}

				.bottom {
					width: 550rpx;
					margin: 0 auto;
					margin-top: 20rpx;
					text-align: center;
					height: 80rpx;
					line-height: 80rpx;
					border-radius: 46rpx;
					background: linear-gradient(to bottom, #AFFFF7, #00D6C0);
					font-size: 36rpx;
					color: #FFFFFF;
					font-weight: 700;
					animation: scaleSize 2s infinite;

					text {
						font-size: 36rpx;
						color: #FFFFFF;
						font-weight: 700;
					}
				}

				@keyframes scaleSize {
					0% {
						transform: scale(1);
					}

					50% {
						transform: scale(1.1);
					}

					100% {
						transform: scale(1);
					}
				}
			}
		}

		.kefu {
			position: fixed;
			width: 80rpx;
			text-align: center;
			bottom: 100rpx;
			right: 40rpx;

			image {
				width: 80rpx;
				height: 80rpx;
				display: flex;
			}

			.desc {
				font-size: 24rpx;
				color: #333333;
				margin-top: -6rpx;
			}
		}

		.beijing {
			position: fixed;
			width: 100%;
			top: 0;
			left: 0;
			height: 100vh;
			background: #000;
			opacity: 0.5;
		}

		.tankuang {
			position: fixed;
			width: 96%;
			top: 28%;
			left: 2%;

			.tankuangbj {
				width: 86%;
				height: 800rpx;
				position: absolute;
				top: 0;
				left: 7%;
			}

			.con {
				position: absolute;
				width: 80%;
				top: 0;
				left: 10%;
				text-align: center;

				.title {
					color: #333333;
					font-weight: 700;
					font-size: 32rpx;
					width: 100%;
					text-align: center;
					margin-top: 60rpx;
				}

				.detail {
					width: 90%;
					margin: 40rpx auto;
					text-align: left;

					.desc {
						color: #666666;
						margin-bottom: 30rpx;

						text {
							color: #447BF8;
						}
					}

					.yuxun {
						color: #427CF8;
						margin-bottom: 30rpx;
					}
				}

				.zhishi {
					width: 90%;
					margin: 80rpx auto 0;
					height: 120rpx;
				}
			}
		}
	}
</style>